package com.szsky.sky.service.impl.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szsky.sky.entity.app.UmcAppSn;
import com.szsky.sky.entity.app.UmcAppVersion;
import com.szsky.sky.mapper.app.UmcAppSnMapper;
import com.szsky.sky.mapper.app.UmcAppVersionMapper;
import com.szsky.sky.service.app.UmcAppVersionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UmcAppVersionServiceImpl extends ServiceImpl<UmcAppVersionMapper, UmcAppVersion> implements UmcAppVersionService {

    @Value("${spring.profiles.active}")
    private String active;
    @Resource
    private UmcAppVersionMapper umcAppVersionMapper;
    @Resource
    private UmcAppSnMapper umcAppSnMapper;

    @Override
    public Map<String, Object> getVersion(String currentVersion, String appType) {
        LambdaQueryWrapper<UmcAppVersion> lam = new LambdaQueryWrapper();
        lam.orderByDesc(UmcAppVersion::getId);
        lam.last("limit 1");
        UmcAppVersion umcAppVersion = umcAppVersionMapper.selectOne(lam);
        Integer versionUpdateFalg = compareVersion(currentVersion, umcAppVersion.getAppVersion());
        Map<String, Object> map = new HashMap<>();
        map.put("updateContext", umcAppVersion.getUpdateContext());
        map.put("forceUpdates", umcAppVersion.getForceUpdates());
        map.put("version", umcAppVersion.getAppVersion());
        if (versionUpdateFalg < 0 && StringUtils.equals(appType, "iOS")) {
            Integer profilesNum = 0;
            if (StringUtils.equals(active, "prod")) {
                profilesNum = 1;
            }
            LambdaQueryWrapper<UmcAppSn> lamAppSn = new LambdaQueryWrapper<>();
            lamAppSn.eq(UmcAppSn::getProfiles, profilesNum);
            lamAppSn.eq(UmcAppSn::getStatus, 0);
            lamAppSn.eq(UmcAppSn::getDeleteStatus, 0);
            lamAppSn.orderByAsc(UmcAppSn::getId);
            lamAppSn.last("LIMIT 1 FOR UPDATE");
            UmcAppSn umcAppSn = umcAppSnMapper.selectOne(lamAppSn);
            map.put("updateFlag", true);
            map.put("appUrl", umcAppSn.getUrl());
            map.put("appUrl", umcAppSn.getUrl());
        } else {
            map.put("updateFlag", false);
        }
        return map;
    }

    /**
     * 比较两个版本号的大小
     *
     * @param version1 第一个版本号
     * @param version2 第二个版本号
     * @return 1表示version1 > version2，-1表示version1 < version2，0表示相等
     */
    public static int compareVersion(String version1, String version2) {
        // 处理空字符串情况
        if (StringUtils.isBlank(version1)) {
            version1 = "0";
        }
        if (StringUtils.isBlank(version2)) {
            version2 = "0";
        }

        // 按点号拆分版本号
        String[] arr1 = version1.split("\\.");
        String[] arr2 = version2.split("\\.");

        int maxLength = Math.max(arr1.length, arr2.length);

        // 逐段比较
        for (int i = 0; i < maxLength; i++) {
            // 超出数组长度的部分用0补充
            int num1 = i < arr1.length ? parseIntSafely(arr1[i]) : 0;
            int num2 = i < arr2.length ? parseIntSafely(arr2[i]) : 0;

            if (num1 > num2) {
                return 1;
            } else if (num1 < num2) {
                return -1;
            }
        }

        // 所有段都相等
        return 0;
    }

    /**
     * 安全地将字符串转换为整数，非数字字符串视为0
     */
    private static int parseIntSafely(String str) {
        try {
            // 处理可能包含的非数字字符（如alpha、beta等版本）
            // 只取前面的数字部分
            StringBuilder numStr = new StringBuilder();
            for (char c : str.toCharArray()) {
                if (Character.isDigit(c)) {
                    numStr.append(c);
                } else {
                    break;
                }
            }
            return numStr.length() > 0 ? Integer.parseInt(numStr.toString()) : 0;
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}
